import math
var
 cache = @[2, 3, 5, 7]
 lastK = 2

proc divable(n: int): bool =
  var i = 2
  while cache[i] ^ 2 <= n:
    if n mod cache[i] == 0:
      return false
    inc(i)
  return true

proc prime*(n: int): int =
  if n == 0:
    raise newException(ValueError, "no zeroth prime")

  if n < cache.len:
    return cache[n - 1]

  let max = 101_000 div 3
  var candidates: array[max, int] = []
  while cache.len < n:
    if divable(lastK * 6 - 1):
      cache.add(lastK * 6 - 1)
    if divable(lastK * 6 + 1):
      cache.add(lastK * 6 + 1)
    lastK.inc
  return cache[n - 1]